<template>
  <div v-loading="loading" class="monthPlanAdd">
    <div class="pub-detail-title-btn">
      <excel ref="exportSelect" file-name="合同明细" is-click-generate="false">
        <a-button slot="excelBtn" @click="exportSelect">导出选中</a-button>
      </excel>
      <excel ref="exportAll" file-name="合同明细" is-click-generate="false">
        <a-button slot="excelBtn" @click="exportAll">导出全部</a-button>
      </excel>
      <ExcelImportButton v-if="isAmendRecord" button-text="导入" icon="upload" @handleSubmit="importFunc" />
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template slot="settlePrice" slot-scope="text, record, index">
        <b-input-number v-if="isAmendRecord" :precision="2" :min="0" class="requiredFormItem"
                        v-model="record.settlePrice"
                        @blur="save(record)"
        />
        <span v-else>{{ record.settlePrice }}</span>
      </template>
      <template slot="contractPrice" slot-scope="text, record, index">
        <b-input-number v-if="isAmendRecord && record.canEdit"
                        :precision="2"
                        :min="0"
                        class="requiredFormItem"
                        v-model="record.contractPrice"
                        @blur="save(record)"
        />
        <span v-else>{{ record.contractPrice }}</span>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
  </div>
</template>
<script>
import { editByDetails, editByDetailsList, parameterDetail } from '@/api/material/contract/parameter'
import benefitAnalysis from '@/api/material/benefitAnalysis/defalut'

export default {
  name: 'a' + Date.now(),
  props: {
    state: {
      type: Number
    },
    id: {
      type: String
    },
    isAmendRecord: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      selectedRows: [],
      pageNo: 1,
      pageSize: 10,
      queryParam: {},
      totalSize: 0,
      selectedRowKeys: [],
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '物资名称',
          dataIndex: 'materialName'
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode'
        },
        {
          title: '规格型号',
          dataIndex: 'materialModel'
        },
        {
          title: '单位',
          dataIndex: 'materialUnit'
        },
        {
          title: '合同单价(税前)(元)',
          width: 160,
          dataIndex: 'contractPrice',
          scopedSlots: { customRender: 'contractPrice' }
        },
        {
          title: '数量',
          dataIndex: 'number'
        },
        {
          title: '合同价款(税前)',
          dataIndex: 'contractNumPrice'
        },
        {
          title: '业主批价',
          dataIndex: 'settlePrice',
          scopedSlots: { customRender: 'settlePrice' }
        },
        {
          title: '收益金额',
          dataIndex: 'incomeAmount'
        },
        {
          title: '利润率(%)',
          dataIndex: 'profitRate'
        },
        {
          title: '备注',
          dataIndex: 'accountRemark',
          scopedSlots: { customRender: 'accountRemark' }
        }
      ],
      editingKey: '',
      data: [],
      selectedId: []
    }
  },
  mounted: function() {
    this.list()
    let a = {
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '唯一标识',
          dataIndex: 'id'
        },
        {
          title: '物资名称',
          dataIndex: 'materialName'
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode'
        },
        {
          title: '规格型号',
          dataIndex: 'materialModel'
        },
        {
          title: '单位',
          dataIndex: 'materialUnit'
        },
        {
          title: '合同单价(税前)(元)',
          width: 160,
          dataIndex: 'contractPrice',
          scopedSlots: { customRender: 'contractPrice' }
        },
        {
          title: '数量',
          dataIndex: 'number'
        },
        {
          title: '合同价款(税前)',
          dataIndex: 'contractNumPrice'
        },
        {
          title: '业主批价',
          dataIndex: 'settlePrice',
          scopedSlots: { customRender: 'settlePrice' }
        },
        {
          title: '收益金额',
          dataIndex: 'incomeAmount'
        },
        {
          title: '利润率(%)',
          dataIndex: 'profitRate'
        },
        {
          title: '备注',
          dataIndex: 'accountRemark',
          scopedSlots: { customRender: 'accountRemark' }
        }
      ]
    }
    this.$refs.exportSelect.tableToExcelFile(a)
    this.$refs.exportAll.tableToExcelFile(a)
  },
  methods: {
    async importFunc(e) {
      this.$console(e)
      let newTable = []
      let checkRes = true
      let error = ''
      e.map(row => {
        if (checkRes && !row['合同单价(税前)(元)']) {
          error = '请填写数据'
          checkRes = false
        }
        if (checkRes && !row['业主批价']) {
          error = '请填写数据'
          checkRes = false
        }
        if (checkRes && !row['唯一标识']) {
          error = '请填写数据'
          checkRes = false
        }

        let columns = [
          {
            title: '序号',
            scopedSlots: { customRender: 'index' }
          },
          {
            title: '唯一标识',
            dataIndex: 'id'
          },
          {
            title: '物资名称',
            dataIndex: 'materialName'
          },
          {
            title: '物料编码',
            dataIndex: 'materialCode'
          },
          {
            title: '规格型号',
            dataIndex: 'materialModel'
          },
          {
            title: '单位',
            dataIndex: 'materialUnit'
          },
          {
            title: '合同单价(税前)(元)',
            width: 160,
            dataIndex: 'contractPrice',
            scopedSlots: { customRender: 'contractPrice' }
          },
          {
            title: '数量',
            dataIndex: 'number'
          },
          {
            title: '合同价款(税前)',
            dataIndex: 'contractNumPrice'
          },
          {
            title: '业主批价',
            dataIndex: 'settlePrice',
            scopedSlots: { customRender: 'settlePrice' }
          },
          {
            title: '收益金额',
            dataIndex: 'incomeAmount'
          },
          {
            title: '利润率(%)',
            dataIndex: 'profitRate'
          },
          {
            title: '备注',
            dataIndex: 'accountRemark',
            scopedSlots: { customRender: 'accountRemark' }
          }
        ]

        let temp = {}
        for (const rowKey in row) {
          let column = columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '合同单价(税前)(元)' && typeof row[rowKey] !== 'number') {
              error = '数据格式错误！'
              checkRes = false
            }
            if (checkRes && rowKey === '业主批价' && typeof row[rowKey] !== 'number') {
              error = '数据格式错误！'
              checkRes = false
            }
          }
        }
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning(error)
      }

      this.loading = true
      newTable.map(v => {
        v.id = v.id.substr(1, v.id.length)
      })
      let res = await editByDetailsList(newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === 'success') {
          this.$noticeSuccess('导入成功！')
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
        this.list()
      }
    },

    exportSelect: function() {
      if (this.selectedRowKeys.length > 0) {
        let temp = this.$clone(this.selectedRows)
        temp.map(v => {
          v.id = 'a' + v.id
          if (!v.contractPrice) v.contractPrice = ''
          if (!v.settlePrice) v.settlePrice = ''
          v.contractPrice = v.contractPrice + ''
          v.settlePrice = v.settlePrice + ''
        })
        this.$refs.exportSelect.setDataAndGenerate(temp)
        this.selectedRows = this.selectedRowKeys = []
      } else {
        this.$message.warning('请选择需要导出的数据')
      }
    },
    exportAll: function() {
      // 参数：查询条件、导出的回调
      if (this.totalSize) {
        this.pageNo = 1
        this.list(this.$refs.exportAll.setDataAndGenerate)
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    initTable() {
      this.pageNo = 1
      this.list()
    },
    async list(callback) {
      this.loading = true
      let res = await parameterDetail({
        pageSize: callback ? this.totalSize : this.pageSize,
        pageNo: this.pageNo,
        id: this.id
      })
      this.loading = false
      if (res.code === 200) {
        if (callback) {
          if (res.data.length) {
            res.data.map(v => {
              v.id = 'a' + v.id
              if (!v.contractPrice) v.contractPrice = ''
              if (!v.settlePrice) v.settlePrice = ''
              v.contractPrice = v.contractPrice + ''
              v.settlePrice = v.settlePrice + ''
            })
            callback(res.data)
          } else {
            this.$message.warning('没有可导出的数据')
          }
          return
        }
        res.data.map(v => {
          if (v.canEdit === null) {
            v.canEdit = !v.contractPrice
          }
        })
        this.data = res.data
        this.totalSize = res.totalSize
      }
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRowKeys = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageSize = pageSize
      this.initTable()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedId = []
      selectedRows.map(i => {
        this.selectedId.push(i.id)
      })
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    save(row) {
      if (!row.contractPrice) {
        return this.$noticeWarning('合同单价(税前)(元)不能为0或空')
      }
      if ((row.contractPrice !== null) && (row.number !== null)) {
        row.contractNumPrice = row.contractPrice * row.number
        row.contractNumPrice = row.contractNumPrice.toFixed(2)
      }
      if ((row.settlePrice !== null) && (row.number !== null) && (row.contractNumPrice !== null)) {
        row.incomeAmount = row.settlePrice * row.number - row.contractNumPrice
        row.incomeAmount = row.incomeAmount.toFixed(2)
        console.log('row.incomeAmount', row.incomeAmount)
        if (parseInt(row.incomeAmount)) {
          row.profitRate = row.incomeAmount / row.contractNumPrice * 100
          row.profitRate = parseInt(row.profitRate)
        } else {
          row.profitRate = 0
        }
      }
      editByDetails(row).then(res => {

        if (res.code !== this.SUCCESS_CODE) {
          this.$noticeWarning(res.message)
        }
      })
    }
  }
}
</script>
